<template>
  <div class="pui-tree">
    <div class="pui-tree_popper" v-if="isPopper">
      <pui-popper theme="light" @onClose="clickOutsideHandle" arrow @onOpen="toggleOpen" :placement="placement" :disabled="disabled">
        <slot></slot>
        <template #popper>
          <pui-tree-children :dataList="dataList" :selectIds="componentRef.selected" @onNodeClick="onNodeClick"></pui-tree-children>
        </template>
      </pui-popper>
    </div>
    <div :class="['pui-tree_box', border && 'border']" v-else>
      <pui-tree-children
        :show="componentRef.autoShow"
        :dataList="dataList"
        :selectIds="componentRef.selected"
        @onNodeClick="onNodeClick"
      ></pui-tree-children>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
  name: 'pui-tree',
});
</script>

<script setup lang="ts">
import { reactive, watch } from 'vue';

import type { Props } from './interface';

const props = withDefaults(defineProps<Props>(), {
  modelValue: {
    label: '',
    value: '',
  },
  size: 'normal',
  type: 'select',
  placement: 'bottom',
  display: '',
  disabled: false,
  clearAble: false,
  isPopper: false,
  show: false,
  border: false,
});

const emits = defineEmits<{
  'update:modelValue': [val: any];
  'onNodeClick': [val: any];
  'update:show': [val: boolean];
}>();

const componentRef = reactive({
  autoShow: false,
  selectedVal: '',
  selectedText: '请选择',
  selected: [] as any,
});

watch(
  () => props.show,
  (v1) => {
    componentRef.autoShow = v1;
    componentRef.selected = [];
    if (v1) {
      props.dataList.map((item: any) => {
        componentRef.selected.push(item.value);
      });
    }
  },
  {
    immediate: true,
  }
);

const toggleOpen = () => {
  console.log(props.show);
  emits('update:show', !props.show);
};

const clickOutsideHandle = () => {
  emits('update:show', false);
};

const onNodeClick = (item: any) => {
  emits('onNodeClick', item);
};
</script>
